<template>
  <div class="medical-record-tree-container">
    <!-- 支持值树形表格 -->
    <Table
      v-loading="loading"
      :columns="columns"
      :data-source="dataSource"
      :count="0"
      :page-no.sync="query.pageNo"
      :page-size.sync="query.pageSize"
      :request="request"
      :form-data.sync="formData"
      :button-group="buttonGroup"
      :table-props="tableProps"
    />

    <!-- 添加支持值对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="添加支持值" width="800px">
      <PageForm
        ref="dialogForm"
        :form-data.sync="ruleForm"
        :list="pageList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>

    <!-- 编辑支持值对话框 -->
    <el-dialog
      :visible.sync="dialogEditVisible"
      title="编辑支持值"
      width="800px"
    >
      <PageForm
        ref="dialogEditForm"
        :form-data.sync="ruleForm"
        :list="pageEditList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>
  </div>
</template>

<script>
import Table from "@/components/Table";
import {
  getMedicalFieldListByConditionApi,
  getFieldSupportTreeApi,
  addFieldSupportApi,
  updateFieldSupportApi,
  deleteFieldSupportApi,
} from "../../../api/config/medical-record";
import PageForm from "@/components/PageForm";
import { treeToArrayOptimized } from "@/utils/treeToArray";

export default {
  name: "MedicalRecordTree",
  components: {
    Table,
    PageForm,
  },
  data() {
    return {
      fieldList: [], // 病历字段列表
      dialogVisible: false,
      dialogEditVisible: false,
      query: {
        pageNo: 1,
        pageSize: 10,
      },
      loading: false,
      dataSource: [],
      count: 0,
      formData: {
        text: "",
      },
      ruleForm: {
        value: "",
        text: "",
        parentId: "",
        sortNum: 1,
      },
    };
  },
  computed: {
    // 将树形数据转换为平铺数组，用于父级选择
    treeArray() {
      if (!this.dataSource || !Array.isArray(this.dataSource)) return [];
      return treeToArrayOptimized(this.dataSource);
    },
    // 表格属性配置，支持树形结构
    tableProps() {
      return {
        rowKey: "id",
        defaultExpandAll: true,
        treeProps: { children: "children", hasChildren: "hasChildren" },
      };
    },
    // 搜索表单配置
    list() {
      return [
        {
          list: [
            {
              span: 4,
              prop: "text",
              component: "input",
              componentProps: {
                placeholder: "请输入支持值名称",
              },
            },
          ],
        },
      ];
    },
    // 表格列配置
    columns() {
      return [
        {
          prop: "value",
          label: "支持值编码",
        },
        {
          prop: "text",
          label: "支持值名称",
          componentProps: {
            formatter: (row) => {
              const level = this.getNodeLevel(row);
              const typeTag = level === 0 ? "分类" : "选项";
              const typeColor = level === 0 ? "#409EFF" : "#67C23A";
              return `${
                row.text
              } <span style="margin-left: 8px; font-size: 12px; color: ${typeColor}; background: ${
                level === 0 ? "#E1F3FF" : "#F0F9FF"
              }; padding: 2px 6px; border-radius: 3px;">${typeTag}</span>`;
            },
          },
          type: "html",
        },
        {
          prop: "sortNum",
          label: "排序",
        },
        {
          prop: "action",
          label: "操作",
          type: "action",
          width: 250,
          componentProps: {
            fixed: "right",
          },
          buttonGroup: [
            {
              label: "添加子项",
              type: "primary",
              size: "small",
              click: (row) => {
                this.resetForm();
                this.ruleForm.parentId = row.id;
                this.dialogVisible = true;
              },
            },
            {
              label: "编辑",
              type: "primary",
              size: "small",
              click: (row) => {
                this.dialogEditVisible = true;
                this.ruleForm = { ...row };
              },
            },
            {
              label: "删除",
              type: "danger",
              size: "small",
              click: (row) => {
                this.$confirm(
                  "此操作将删除此支持值及其所有子项, 是否继续?",
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }
                ).then(async () => {
                  try {
                    await deleteFieldSupportApi({ id: row.id });
                    this.$message.success("删除成功");
                    this.request();
                  } catch (error) {
                    this.$message.error("删除失败");
                  }
                });
              },
            },
          ],
        },
      ];
    },
    // 按钮组配置
    buttonGroup() {
      return [
        {
          label: "添加",
          type: "primary",
          click: () => {
            this.resetForm();
            this.ruleForm.parentId = 0;
            this.dialogVisible = true;
          },
        },
      ];
    },
    // 添加表单配置
    pageList() {
      return [
        {
          list: [
            {
              span: 24,
              prop: "parentId",
              label: "父级支持值",
              component: "Treeselect",
              treeSelectList: [
                {
                  id: 0,
                  text: "顶级分类",
                  children: this.dataSource || [],
                },
              ],
              normalizer(node) {
                if (node.children && !node.children.length) {
                  delete node.children;
                }
                // 兼容不同的数据结构
                return {
                  id: node.id,
                  label: node.text,
                  children: node.children,
                };
              },
              componentProps: {
                placeholder: "请选择父级支持值",
              },
            },
            {
              span: 24,
              prop: "value",
              label: "支持值编码",
              component: "input",
              componentProps: {
                placeholder: "请输入支持值编码",
              },
            },
            {
              span: 24,
              prop: "text",
              label: "支持值名称",
              component: "input",
              componentProps: {
                placeholder: "请输入支持值名称",
              },
            },
            {
              span: 24,
              prop: "sortNum",
              label: "排序",
              component: "input",
              componentProps: {
                type: "number",
                placeholder: "请输入排序",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogForm) {
                      this.$refs.dialogForm.validate((valid) => {
                        if (valid) {
                          this.handleSave();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 编辑表单配置
    pageEditList() {
      return [
        {
          list: [
            {
              span: 24,
              prop: "parentId",
              label: "父级支持值",
              component: "Treeselect",
              treeSelectList: [
                {
                  id: 0,
                  text: "顶级分类",
                  children: this.dataSource
                    ? this.filterCurrentNode(this.dataSource, this.ruleForm.id)
                    : [],
                },
              ],
              normalizer(node) {
                if (node.children && !node.children.length) {
                  delete node.children;
                }
                // 兼容不同的数据结构
                return {
                  id: node.id,
                  label: node.text,
                  children: node.children,
                };
              },
              componentProps: {
                placeholder: "请选择父级支持值",
              },
            },
            {
              span: 24,
              prop: "value",
              label: "支持值编码",
              component: "input",
              componentProps: {
                placeholder: "请输入支持值编码",
              },
            },
            {
              span: 24,
              prop: "text",
              label: "支持值名称",
              component: "input",
              componentProps: {
                placeholder: "请输入支持值名称",
              },
            },
            {
              span: 24,
              prop: "sortNum",
              label: "排序",
              component: "input",
              componentProps: {
                type: "number",
                placeholder: "请输入排序",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogEditVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogEditForm) {
                      this.$refs.dialogEditForm.validate((valid) => {
                        if (valid) {
                          this.handleUpdate();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 表单验证规则
    dialogRules() {
      return {
        value: [
          { required: true, message: "请输入支持值编码", trigger: "blur" },
        ],
        text: [
          { required: true, message: "请输入支持值名称", trigger: "blur" },
        ],
        sortNum: [{ required: true, message: "请输入排序", trigger: "blur" }],
      };
    },
  },
  mounted() {
    this.loadFieldList();
  },
  methods: {
    // 过滤当前节点（避免自己选择自己作为父节点）
    filterCurrentNode(nodes, currentId) {
      return nodes
        .filter((node) => node.id !== currentId)
        .map((node) => ({
          ...node,
          children: node.children
            ? this.filterCurrentNode(node.children, currentId)
            : [],
        }));
    },
    // 加载病历字段列表
    async loadFieldList() {
      try {
        const res = await getMedicalFieldListByConditionApi({
          pageNo: 1,
          pageSize: 100000,
        });
        if (res.code === 200) {
          this.fieldList = res.data.list || [];
        }
      } catch (error) {
        console.error(error);
        this.$message.error("获取病历字段列表失败");
      }
    },
    // 字段选择变化
    handleFieldChange() {
      this.request();
    },
    // 获取节点层级
    getNodeLevel(node) {
      let level = 0;
      let currentNode = node;
      while (currentNode.parentId !== 0) {
        level++;
        // 在树形数组中查找父节点
        currentNode = this.treeArray.find(
          (item) => item.id === currentNode.parentId
        );
        if (!currentNode) break;
      }
      return level;
    },
    // 请求数据
    async request() {
      try {
        if (this.loading) return;

        this.loading = true;

        const res = await getFieldSupportTreeApi({
          fieldId: this.$route.query.fieldId,
        });

        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.dataSource = res.data || [];
        this.count = this.dataSource.length;
      } catch (error) {
        console.log(error);
        this.$message.error("获取支持值列表失败");
      } finally {
        this.loading = false;
      }
    },
    // 处理保存
    async handleSave() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await addFieldSupportApi({
          ...this.ruleForm,
          fieldId: this.$route.query.fieldId,
        });

        this.loading = false;

        if (res.code === 200) {
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 处理更新
    async handleUpdate() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await updateFieldSupportApi({
          ...this.ruleForm,
          fieldId: this.$route.query.fieldId,
        });

        this.loading = false;

        if (res.code === 200) {
          this.$message.success("更新成功");
          this.dialogEditVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 重置表单
    resetForm() {
      this.ruleForm = {
        value: "",
        text: "",
        parentId: "",
        sortNum: "",
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.medical-record-tree-container {
  padding: 20px;

  .field-selector-card {
    margin-bottom: 20px;

    .field-selector {
      display: flex;
      align-items: center;

      .label {
        font-weight: 500;
        margin-right: 10px;
      }
    }
  }
}
</style>
